import { Request, Response } from 'express'
import noticesService from "../../service/noticesService";
import { validateCreateForm } from './validate'

class NoticesController {
  // 创建公告
  async createNotices(req: Request, res: Response) {
    const form = req.body
    const msg = validateCreateForm(form)
    if (msg) return res.gem(msg)
    const saveRes = await noticesService.save(form)
    if (!saveRes) return res.gem('公告发布失败！')
    res.gsm('公告发布成功！')
  }

  // 根据 发布者(模糊匹配) + 接收者 进行查询（分页）
  async findByNameKeyAndSubscriber(req: Request, res: Response) {
    const form = req.body
    let label = '', value = ''
    // 取出label和对应的value
    Object.keys(form).forEach(item => {
      if (item.includes('publisher') || item.includes('title')) {
        label = item
        value = form[item]
      }
    })
    if (form.subscriber === '3') form.subscriber = ''
    const page_num = parseInt(req.body.page_num) || 1
    const page_size = parseInt(req.body.page_size) || 10
    const skip = (page_num - 1) * page_size

    const users = await noticesService.findByNameKeyAndSubscriber(label, value, form.subscriber, skip, page_size)
    const count = await noticesService.findByNameKeyAndSubscriberCount(label, value, form.subscriber)

    if (!users) res.gem('查无数据！')
    res.gsmdl(count, users)
  }

  // 删除公告
  async deleteNotices(req: Request, res: Response) {
    const { id } = req.params
    const notice = await noticesService.findById(id)
    if (!notice) return res.gem('该公告不存在！')
    const result = await noticesService.deleteById(id)
    if (result.affected >= 1) {
      return res.gsm('删除公告成功！')
    } else {
      return res.gem('删除公告失败！')
    }
  }

  // 获取接收者所能查看的最新一条公告
  async getNewNotices(req: Request, res: Response) {
    const { subscriber } = req.params
    const result = await noticesService.findBySubscriber(subscriber)
    if (!result) return res.gem('查无公告！')
    res.gsmd(result)
  }

  // 获取用户的公告，（例如：教师角色的所有可查看的公告）
  // 根据发布者+标题（模糊匹配）进行查询
  async getRoleNotice(req: Request, res: Response) {
    const form = req.body
    // console.log(form);
    let label = '', value = ''
    // 取出label和对应的value
    Object.keys(form).forEach(item => {
      if (item.includes('publisher') || item.includes('title')) {
        label = item
        value = form[item]
      }
    })
    const page_num = parseInt(req.body.page_num) || 1
    const page_size = parseInt(req.body.page_size) || 10
    const skip = (page_num - 1) * page_size
  
    // console.log(label, value, form.subscriber,);

    const notices = await noticesService.findRoleNotice(label, value, form.subscriber, skip, page_size)
    const count = await noticesService.findRoleNoticeCount(label, value, form.subscriber)

    if (!notices) res.gem('查无数据！')
    res.gsmdl(count, notices)
  }
}

export default new NoticesController()